import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-FactoryTesting',
	templateUrl: './factory-testing.component.html',
})
export class FactoryTestingComponent implements OnInit {
	tableData:any[] = []; //table数据
	resultTableData:any[] = [] //客户端分页数据暂存
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	userNameList:any[] = []; //用户数据集合
	userName:string = ''; //用户名
	startTime:string = '';//开始时间
	endTime:string = '';	//结束时间
	carNumber:string = '';	//车牌号码
	deviceId:string = '';	//设备ID，车牌ID
	useType:any = '';	//接口使用类型
	type:any = ''; //状态类型
	constructor(private jsonApiService: JsonApiService) {}
	
	
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.startTime=time.startTime;
		this.endTime=time.endTime;
		this.search_data();
	}
	//刷新
	refresh(){
		this.load();
	}
	ngOnInit() {
		this.initCarTree();
		// this.load();	
	}
	//初始化车辆
    initCarTree() {
        System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
            System.import('assets/js/select2-zh-CN.js').then(() => {
                var that = this;
                $("#carNumberSelect2").select2({
                    language: "zh-CN",
                    placeholder: "请选择",
                    minimumInputLength: 2,      //最少2个字符，select2才显示查询的内容
                    ajax: {
                        url: config.BaseURL + "stats/carListByCarNumber.html",
                        dataType: 'json',
                        delay: 50,
                        method: "POST",
                        xhrFields: { withCredentials: true },
                        data: function (params) {
                            return {
                                "carNumber": params.term // search term
                            };
                        },
                        processResults: function(data, params) {
							var options = new Array();
							// 小于10个数量才判断重复
							if(data.data.length<=10){
								let arr = []
								let sameCar = []
								// 判断相同的车牌号
								for (let index = 0; index < data.data.length; index++) {
									let car = data.data[index];
									if(arr.indexOf(car.carNumber)!=-1){
										sameCar.push(car.carNumber)
									}else{
										arr.push(car.carNumber);
									}
								}
								$(data.data).each(function(index, car) {
									if(sameCar.indexOf(car.carNumber)!=-1){
										options.push({
											id: car.deviceId,
											text: car.carNumber+"["+car.parentName+"]"
										})
									}else{
										options.push({
											id: car.deviceId,
											text: car.carNumber
										})
									}
								});
							}else{
								$(data.data).each(function(index, car) {
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								});
							}
							return {
								results: options //获取查询后的结果
							};
						},
                        cache: true
                    },
                    templateResult: this.formatRepo
                }).on("select2:select", function (e) {
                    var data = e.params.data;
                    that.deviceId = data.id;
                    if(data.text.indexOf('[') > 0){
						that.carNumber = data.text.split('[')[0];
					} else {
						that.carNumber = data.text;
					}
                });
            })
        })
	}
	//select2 格式回调函数
    formatRepo(state) {
        if (!state.id) { return state.text };
        var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
        return $state;
	}
	//清除车辆选中值
    del_carNumber() {
        this.deviceId = '';
        this.carNumber = '';
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2').val("");
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title", "");
        $("#select2-carNumberSelect2-container").prepend(str);
    }
	//查询
	search_data(){
		this.curPage = 1;
		this.load();
	}
	//加载list数据
	load() {
		var data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				startTime:this.startTime,
				endTime:this.endTime,
				searchKey:this.searchKey,
				deviceId:this.deviceId,
				useType:this.useType,
				type:this.type,
				export: '0' //是否导出 0不是
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http('logForInFactory/data.html', reqdata).subscribe(result => {
			this.resultTableData=result.exhibitDatas;
			this.totalCount=result.recordCount;
			
		})
	}
	table_search(){
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
	}
	client_pages(start,length){
		this.resultTableData = this.tableData.slice(start,start+length);
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	
	// 删除
	// deleteRow(row){
	// 	this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(()=>{
	// 		let reqdata = 'id=' + row.id;
	// 		this.jsonApiService.http("deviceCoefLog/deleteDeviceCoefLog.html",reqdata).subscribe(data => {
	// 			this.jsonApiService.message(data.message)
	// 			if(data.success){
	// 				this.load();
	// 			}
	// 		})
	// 	})
	// }
	// 数据导出
	exportData(){
		const param = {		
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				startTime:this.startTime,
				endTime:this.endTime,
				searchKey:this.searchKey,
				deviceId:this.deviceId,
				useType:this.useType,
				type:this.type,
				export: '1' //是否导出 1是
			}
		}
		let timeCheck = common.correctTime(param.parameters, ['export'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(param, 'gridPager', config.BaseURL + 'logForInFactory/data.html')		
    }
	
}